package models;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.User;

public class UserModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "user_";
	
	private static UserModel instance = null;
	
	public static UserModel getInstance() {
		if (instance == null) {
			instance = new UserModel();
		}
		
		return instance;
	}
	
	private UserModel() {
		try {
			ObjectifyService.register(User.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ArrayList<User> list(int page, int limit) {
		ArrayList<User> users = new ArrayList<User>();
		
		int start = (page - 1) * limit;
		Query<User> q = ofy.query(User.class).limit(limit).offset(start);
		for (User user: q) {
			users.add(user);
		}
		
		return users;
	}
	
	public void insert(User user) {
		if (cache != null) {
			cache.put(prefix + user.getId(), user);
		}
		
		if (cache != null) {
			cache.put(prefix + user.getUsername(), user);
		}
		
		ofy.put(user);
	}
	
	public void delete(User user) {
		if (cache != null && cache.containsKey(prefix + user.getId())) {
			cache.remove(prefix + user.getId());
		}
		
		if (cache != null && cache.containsKey(prefix + user.getUsername())) {
			cache.remove(prefix + user.getUsername());
		}
		
		ofy.delete(user);
	}
	
	public User getUser(String id) {
		User user = new User();
		if (cache != null && cache.containsKey(prefix + id)) {
			user = (User) cache.get(prefix + id);
		} else {
			try {
				user = ofy.get(new Key<User>(User.class, id));
				cache.put(prefix + id, user);
			} catch (Exception e) {
				user = null;
			}
		}
		return user;
	}
	
	public User getByUsername(String username) {
		User user = new User();
		
		if (cache != null && cache.containsKey(prefix + username)) {
			user = (User) cache.get(prefix + username);
		} else {
			user = (User) ofy.query(User.class).filter("username", username).get();
		}
		
		return user;
	}
	
	public boolean checkUserExists(String username) {
		boolean exists = false;
		User user = getByUsername(username);
		if (user != null) {
			exists = true;
		}
		return exists;
	}
}
